#include "mystdio.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>


#define DEL_MODE 0666

myfile* my_fopen(const char* path,const char* mode)
{
    int fd = 0;
    int flag = 0;
    if(strcmp(mode,"w") == 0)
    {
        flag|=(O_CREAT | O_WRONLY | O_TRUNC);
    }
    else if(strcmp(mode,"r") == 0)
    {
        flag|=O_RDONLY;
    }
    else if(strcmp(mode,"a") == 0)
    {
        flag|=(O_WRONLY | O_APPEND | O_CREAT);
    }
    else 
    {
        //do nothing
    }
    

    //判断是否重新打开文件
    if(flag & O_CREAT)
    {
        fd = open(path,flag,0666);
    }
    else 
    {
        fd = open(path,flag);
    }
    if(fd < 0)
    {
        errno = 2;
        return NULL;
    }

    myfile* stream = (myfile*)malloc(sizeof(myfile));
    if(!stream)
    {
        errno = 3;
        return NULL;
    }
    stream->fileno = fd;
    stream->end = 0;
    stream->flag =  FFLUSH_LINE;
    return stream;
}

int my_fwrite(const char* ptr,int size,myfile* stream)
{
    //先将数据拷贝到缓冲区
    memcpy(stream->buffer + stream->end,ptr,size);
    stream->end += size;

    //特殊刷新标志
    if(stream->flag == FFLUSH_LINE
        && stream->buffer[stream->end-1] == '\n'
         && stream->end > 0)
    {
        my_fflush(stream);
    }

    return size;
}

int my_fflush(myfile* stream)
{
    if(stream->end > 0)
    {
        write(stream->fileno,stream->buffer,stream->end);
        stream->end = 0;
    }
}

int my_fclose(myfile* stream)
{
    my_fflush(stream);
    return close(stream->fileno);
}
